package com.cxyzy.listviewdemo

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initListView()
    }

    private fun initListView() {
        var dataList = getData()
        val adapter = ListViewAdapter(this)
        adapter.setData(dataList)
        listView.adapter = adapter
        //隐藏自带的分隔符，在ListViewAdapter对应的布局里自定义分隔符，这样可以更灵活。
        listView.divider = null
        //添加点击事件
        listView.setOnItemClickListener { adapterView, _, position, _ ->
            val text = adapterView.getItemAtPosition(position).toString()
            toast(text)
        }
    }

    private fun getData(): List<String> {
        val dataList = ArrayList<String>()
        for (index in 0 until 100) {
            val text = " 数据$index "
            dataList.add(text)
        }
        return dataList
    }

    /**
     * 显示toast短暂提示
     */
    private fun toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}